package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author ChenPi
 * @since 2024/09/27 13:34
 */
@Data
@AllArgsConstructor
public class SimpleRedisLock implements ILock {

    // Spring 应用名称
    private static final String PROJECT_NAME = "hmdp:";
    private static final String KEY_PREFIX = PROJECT_NAME + "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    private String name;
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean tryLock(Long timeSec) {
        // 获取线程标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeSec, TimeUnit.SECONDS);

        return BooleanUtil.isTrue(success);
    }

    @Override
    public void unlock() {
    try {
        // 打印调试信息
        String lockKey = KEY_PREFIX + name;
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        System.out.println("Unlocking lock with key: " + lockKey);
        System.out.println("Lock ID: " + threadId);
// 打印脚本内容以供调试
        System.out.println("Executing script: " + UNLOCK_SCRIPT.getScriptAsString());
        // 执行脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(lockKey),
                threadId
        );

    } catch (Exception e) {
        // 打印异常信息
        e.printStackTrace();
        // 根据需要进行其他处理
    }
}

    // @Override
    // public void unlock() {
    //     // 获取线程标识
    //     String threadId = ID_PREFIX + Thread.currentThread().getId();
    //     // 获取锁标识
    //     String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
    //     if (threadId.equals(id)) {
    //         // 释放锁
    //         stringRedisTemplate.delete(KEY_PREFIX + name);
    //     }
    // }
}
